using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TrafficTrouble.Components;
using System.IO;

namespace TrafficTrouble
{
    public static class Util
    {
        public static int Width<T>(this T[,] array)
        {
            return array.GetLength(0);
        }
        public static int Height<T>(this T[,] array)
        {
            return array.GetLength(1);
        }

        public static Grid GetLevelFromFile(string levelName)
        {
            Grid level = null;
            using ( Stream stream = Microsoft.Xna.Framework.TitleContainer.OpenStream("Levels/" + levelName + ".ttl"))
            {
                int version = stream.ReadByte();
                for (int i = 0; i < Environment.NewLine.Length; i++)
                    stream.ReadByte();
                if (true)//version == 1)
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        string[] gridInfo = reader.ReadLine().Split(' ');
                        int levelWidth = int.Parse(gridInfo[0]),
                            levelHeight = int.Parse(gridInfo[1]),
                            numTotalCars = int.Parse(gridInfo[2]),
                            numPlayerCars = int.Parse(gridInfo[3]);

                        level = new Grid(levelName, levelWidth, levelHeight);

                        for (int i = 0; i < numTotalCars; i++)
                        {
                            string[] carInfo = reader.ReadLine().Split(' ');
                            int carX = int.Parse(carInfo[0]),
                                carY = int.Parse(carInfo[1]),
                                carLength = int.Parse(carInfo[2]);
                            bool vertical = carInfo[3].ToLower().StartsWith("v");

                            level.AddCar(new Car(level, carLength, vertical, carX, carY, (i < numPlayerCars)));
                        }
                    }
                }
                else throw new Exception("Unknown level version number '" + version
                        + ". (TrafficTrouble.Util.GetLevelFromFile(string)).");
            }
            return level;
        }
    }
}
